import {useState, useEffect} from 'react';
import {connect} from "react-redux";
import {View, Text} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import {Loading, Empty, Overlay, Tag, CircleProgress, Button} from '@nutui/nutui-react-taro';
import {AngleDoubleRight} from '@nutui/icons-react-taro'
import {
    AtIcon,
    AtTag,
    AtCard,
    AtTabs,
    AtTabsPane,
    AtButton,
    AtModal,
    AtModalHeader,
    AtModalContent,
    AtModalAction
} from "taro-ui";
import './detail.less'
import getBaseUrl from "../../service/baseUrl";

const base = getBaseUrl();

function Index(props) {
    const isLogin = Taro.getStorageSync("isLogin");
    // const params = getCurrentInstance()?.router?.params || {}; // 路由参数
    const [isOpened, setOpen] = useState()
    const [currentKey, setKey] = useState(0)
    const {dispatch, currentStation = {}, rateDetail = [], loading} = props;
    console.log('站详情前端展示数据', currentStation);
    console.log('loading', loading);
    const currentTimeRange = rateDetail.find((i) => i.flag) || {};
    const timeStr = currentTimeRange?.timeStr ? currentTimeRange?.timeStr.replace('-', '~') : '';
    const {
        stationName,
        openType,
        stationAddress,
        price,
        gunCountInfo: {
            fastALL: fastAll,
            fastNum: fastFree,
            slowALL: slowAll,
            slowNum: slowFree,
        } = {},
        distance,
        latitude,
        longitude,
        piles = []
    } = currentStation;
    useEffect(() => {
        dispatch({
            type: 'stations/initDetail',
            payload: {
                current: {
                    ...currentStation
                }
            }
        })
    }, [])
    const WrapperStyle = {
        display: 'flex',
        height: '100%',
        alignItems: 'center',
        justifyContent: 'center'
    }
    const tabList = [{title: '桩详情'}, {title: '站详情'}];

    function handleClick(value) {
        setKey(value)
    }

    function makePhone(e) {
        e.stopPropagation();
        if (currentStation.stationTel) {
            Taro.makePhoneCall({
                phoneNumber: currentStation?.stationTel.toString(),
            });
        } else {
            Taro.showToast({
                title: "暂未收录电站服务电话",
                icon: "none",
                duration: 1000,
            });
        }
    }

    function formatType(type) {
        switch (type) {
            case '空闲中':
                return {
                    icon: 'free_fill',
                    text: '空闲中',
                    className: 'cardContentRightFree'
                };
            case '已插枪':
                return {
                    icon: 'dianqiangguanli',
                    text: '已插枪',
                    className: 'cardContentRightBusy'
                };
            case '充电中':
                return {
                    icon: 'chongdian',
                    text: '充电中',
                    className: 'cardContentRightCharging'
                };
            case '离线':
                return {
                    icon: 'lixianbaobiao',
                    text: '离线',
                    className: 'cardContentRightOff'
                };
            case '故障':
                return {
                    icon: 'guzhang',
                    text: '故障',
                    className: 'cardContentRightBroken'
                }
            default:
                return ''
        }
    }

    console.log('详情', props);

    // const AAA = String.fromCharCode(Number(1));
    function getHour(minutes) {
        let hour = '00';
        if (minutes >= 600) {
            hour = Math.floor(minutes / 60)
        } else if (minutes >= 60) {
            hour = '0' + Math.floor(minutes / 60);
        } else {
            hour = '00'
        }
        return hour;
    }

    function getMinute(minutes) {
        // let minute = '00';
        return (minutes % 60) >= 10 ? (minutes % 60) : '0' + (minutes % 60);
    }

    return (
        <View className='stationDetailWrap'>
            {
                loading ?
                    <Overlay
                        visible={loading}
                        style={{
                            backgroundColor: '#ffffff',
                            '--nutui-overlay-zIndex': 2000,
                        }}
                    >
                        <div className='wrapper' style={WrapperStyle}>
                            <Loading direction='vertical'>页面加载中...</Loading>
                        </div>
                    </Overlay> :
                    <View>
                        <View className='stationInfo'>
                            <div className='title'>
                                <Tag type='info' round>{openType}</Tag>
                                &nbsp;{stationName}
                            </div>
                            <div className='position'>
                                <View className='address'>
                                    <AtIcon value='map-pin' size='16'></AtIcon>
                                    <Text>
                                        {stationAddress}
                                    </Text>
                                </View>
                                <View onClick={() => {
                                    Taro.openLocation({
                                        latitude: parseFloat(latitude),	//维度
                                        longitude: parseFloat(longitude), //经度
                                        name: stationName || "",	//目的地定位名称
                                        scale: 12,	//缩放比例
                                        address: stationAddress || ""	//导航详细地址
                                    });
                                }}
                                >
                                    <AtIcon prefixClass='icon' value='daohang' size='16' color='#0091FF'/>
                                    <Text style={{whiteSpace: 'nowrap'}}>
                                        {distance && distance.toFixed(2)} km
                                    </Text>
                                </View>
                            </div>
                            <div className='type'>
                                <View className='typeCard'>
                                    <AtTag size='small' type='primary' active circle>快</AtTag>&nbsp;&nbsp;
                                    <Text style={{color: '#00E39A'}}>{fastFree}</Text>&nbsp;
                                    <Text style={{color: '#767E8E'}}>/</Text>&nbsp;
                                    <Text>{fastAll}</Text>
                                </View>
                                <View className='typeCard'>
                                    <AtTag size='small' active circle>慢</AtTag>&nbsp;&nbsp;
                                    <Text style={{color: '#00E39A'}}>{slowFree}</Text>&nbsp;
                                    <Text style={{color: '#767E8E'}}>/</Text>&nbsp;
                                    <Text>{slowAll}</Text>
                                </View>
                            </div>
                        </View>
                        <View className='stationInfo'>
                            <div className='title'>
                                费用说明
                            </div>
                            <div className='position'>
                                <View className='address'>
                                    <Text>
                                        当前计费时段: {timeStr}
                                    </Text>
                                </View>
                                <View onClick={() => Taro.navigateTo({url: '/moduleA/pages/rate/index'})}>
                                    <Text>
                                        计费详情
                                    </Text>
                                    &nbsp;
                                    <AtIcon value='chevron-right' size='18' color='#767E8E'/>
                                </View>
                            </div>
                            <div className='type'>
                                <View style={{color: '#FA6400', fontWeight: 'bold'}}>
                                    {price && price.toFixed(2)}
                                    <Text style={{fontSize: '24rpx'}}>元/度</Text>
                                </View>
                            </div>
                        </View>
                        <View className='stationPiles'>
                            <AtTabs current={currentKey} tabList={tabList} onClick={(val) => handleClick(val)}>
                                <AtTabsPane current={currentKey} index={0}>
                                    {
                                        piles.length ?
                                            piles.map((i) =>
                                                <AtCard
                                                    title={i.pileName}
                                                >
                                                    {
                                                        i.gunInfo && i.gunInfo.length ? i.gunInfo.map((l) =>
                                                            <View
                                                                className='cardContent'
                                                                onClick={() => {
                                                                    if (l.gunStatus === '已插枪' || l.gunStatus === '空闲中') {
                                                                        dispatch({
                                                                            type: 'stations/backToPile',
                                                                            payload: {
                                                                                pileCode: i.pileCode,
                                                                                gunCode: l.gunIndex,
                                                                                needJump: true
                                                                            }
                                                                        })
                                                                        // Taro.navigateTo({url: "/pages/pile/index"})
                                                                    } else {
                                                                        Taro.showToast({
                                                                            title: `该充电枪${l.gunStatus},暂时无法提供服务`,
                                                                            icon: 'none'
                                                                        })
                                                                    }
                                                                }}
                                                            >
                                                                <View className='cardContentLeft'>
                                                                    <View className='line'>
                                                                        {String.fromCharCode(Number(l.gunIndex) + 64)}枪
                                                                        {
                                                                            l.gunStatus === '已插枪' || l.gunStatus === '空闲中' ?
                                                                                <Tag style={{marginLeft: '6px'}}
                                                                                     background='#00e39a'
                                                                                     color='#ffffff'
                                                                                     round>可充电</Tag> : null
                                                                        }
                                                                        {i.scheduledChargingFlag ?
                                                                          l.gunStatus === '空闲中' || l.gunStatus === '充电中' ?
                                                                                <Tag
                                                                                    style={{
                                                                                        marginLeft: '6px',
                                                                                        // display: 'flex',
                                                                                        // justifyContent: 'space-between',
                                                                                        // alignItems: 'center',
                                                                                        // lineHeight: 1
                                                                                    }}
                                                                                    background='#f8322b'
                                                                                    // color='#ffffff'
                                                                                    plain
                                                                                    onClick={(e) => {
                                                                                        e.stopPropagation();
                                                                                        console.log('点击预约充电');
                                                                                        if (!isLogin) {
                                                                                            setOpen(true)
                                                                                            // e.preventDefault();
                                                                                        } else {
                                                                                            Taro.navigateTo({
                                                                                                url: `/moduleB/pages/bookCharge/index?pileCode=${i.pileCode}&gunCode=${l.gunIndex}&stationId=${currentStation.stationId}&stationName=${currentStation?.stationName}`
                                                                                            })
                                                                                        }
                                                                                    }}
                                                                                >
                                                                                    <View
                                                                                        style={{
                                                                                            height: '100%',
                                                                                            width: '100%',
                                                                                            display: 'flex',
                                                                                            justifyContent: 'space-between',
                                                                                            alignItems: 'center',
                                                                                            lineHeight: 1
                                                                                        }}>
                                                                                        <View>
                                                                                            预约充电
                                                                                        </View>
                                                                                        <View>
                                                                                            <AngleDoubleRight width="28rpx"/>
                                                                                        </View>
                                                                                    </View>
                                                                                </Tag> : null  : null
                                                                        }
                                                                    </View>
                                                                    <View className='line'>{l.gunCode}</View>
                                                                    <View className='line'>
                                                                        <Tag background='#EEF6EE' color='black'
                                                                             round>{l.gunType || ''}</Tag>
                                                                        &nbsp; &nbsp;
                                                                        <Tag background='#EEF6EE' color='black'
                                                                             round>{l.power ? `${l.power}Kw` : '-'}</Tag>
                                                                    </View>
                                                                </View>
                                                                {
                                                                    l.gunStatus === '充电中'  && l.gunType !== '交流慢充' ?
                                                                        <View>
                                                                            <CircleProgress radius={38} strokeWidth={10}
                                                                                            percent={parseInt(l.soc)}
                                                                                            color="#1988fa">
                                                                                {l.soc ? <div>{l.soc}%</div> : null}
                                                                                <div style={{
                                                                                    fontSize: '12px',
                                                                                    color: 'var(--nutui-black-10)'
                                                                                }}>
                                                                                    充电中
                                                                                </div>
                                                                            </CircleProgress>
                                                                            {l.remainTime ?
                                                                                <div>还需{getHour(l.remainTime)}:{getMinute(l.remainTime)}分</div> : null}
                                                                        </View> : <View
                                                                            className={formatType(l.gunStatus)?.className}>
                                                                            <View>
                                                                                <AtIcon prefixClass='icon'
                                                                                        value={formatType(l.gunStatus)?.icon}
                                                                                        size='24'
                                                                                        color='#ffffff'/>
                                                                            </View>
                                                                            <View>
                                                                                {formatType(l.gunStatus)?.text}
                                                                            </View>
                                                                        </View>
                                                                }
                                                            </View>
                                                        ) : null
                                                    }
                                                </AtCard>
                                            ) :
                                            <Empty/>
                                    }
                                </AtTabsPane>
                                <AtTabsPane current={currentKey} index={1}>
                                    <View className='optInfo'>
                                        <View>开放时间: {currentStation.busineHours}</View>
                                        <View>电站品牌: 金冠智充</View>
                                        <View>服务电话:
                                            <Text style={{color: '#237AF5'}} onClick={(e) => makePhone(e)}>
                                                <AtIcon value='phone' size={20}/>
                                                {currentStation.stationTel}
                                            </Text>
                                        </View>
                                    </View>
                                </AtTabsPane>
                            </AtTabs>
                        </View>
                    </View>
            }
            <View className='scanPageFooter'>
                <AtButton
                    onClick={() => {
                        // Taro.navigateToMiniProgram({
                        //     appId: 'wx6aa5afd58e222b63',
                        //     path: 'pages/index/index',
                        //     extraData: {
                        //         foo: 'bar'
                        //     },
                        //     envVersion: 'develop',
                        //     success: function(res) {
                        //         console.log('打开成功', res);
                        //         // 打开成功
                        //     }
                        // })
                        Taro.scanCode({
                            success: (res) => {
                                console.log('扫一扫成功的结果返回', res);
                                if (res.result) {  // 普通二维码
                                    const paramStr = unescape(res?.result).split('code=').length > 1 ? unescape(res?.result).split('code=')[1] : '';
                                    const pileCode = paramStr.slice(0, -2);
                                    let gunCode = paramStr.slice(-2);
                                    if (gunCode.startsWith('0')) gunCode = gunCode.slice(-1);
                                    console.log('pileCode普通', pileCode);
                                    console.log('gunCode普通', gunCode);
                                    //扫码成功后的操作
                                    if (pileCode && gunCode) {
                                        dispatch({
                                            type: 'stations/jumpToPile',
                                            payload: {
                                                pileCode,
                                                gunCode
                                                // pileId
                                            }
                                        });
                                        setTimeout(() => Taro.reLaunch({url: '/moduleA/pages/pile/index'}), 300)
                                    }
                                } else if (res.path) {  // 小程序码
                                    const paramStr = unescape(res?.path).split('scene=').length > 1 ? unescape(res?.path).split('scene=')[1] : '';
                                    const pileStr = paramStr.split('&').length > 1 ? paramStr.split('&')[0] : ''
                                    const gunStr = paramStr.split('&').length > 1 ? paramStr.split('&')[1] : ''
                                    console.log('paramStr', paramStr);
                                    console.log('pileStr', pileStr);
                                    console.log('gunStr', gunStr);
                                    const pileCode = pileStr.split('=').length > 1 ? pileStr.split('=')[1] : '';
                                    const gunCode = gunStr.split('=').length > 1 ? gunStr.split('=')[1] : '';
                                    console.log('pileCode葵花', pileCode);
                                    console.log('gunCode葵花', gunCode);
                                    //扫码成功后的操作
                                    if (pileCode && gunCode) {
                                        dispatch({
                                            type: 'stations/jumpToPile',
                                            payload: {
                                                pileCode,
                                                gunCode
                                                // pileId
                                            }
                                        });
                                        setTimeout(() => Taro.reLaunch({url: '/moduleA/pages/pile/index'}), 300)
                                    }
                                }
                            },
                            fail: () => {

                            }
                        })
                    }}
                >扫码充电</AtButton>
            </View>
            <AtModal isOpened={isOpened} closeOnClickOverlay={false}>
                <AtModalHeader>温馨提示</AtModalHeader>
                <AtModalContent>
                    <View className='modalContent'>
                        请先登录再进行操作
                    </View>
                </AtModalContent>
                <AtModalAction>
                    <View className='modalFooter'>
                        <AtButton
                            plain
                            style={{border: 'none'}}
                            onClick={() => {
                                Taro.reLaunch({
                                    url: '/pages/index/index'
                                });
                                setOpen(false)
                            }}
                        >取消</AtButton>
                        <AtButton
                            plain
                            style={{border: 'none'}}
                            openType='getPhoneNumber'
                            onGetPhoneNumber={(e) => {
                                const accessToken = Taro.getStorageSync('access_token')
                                const {detail: {iv, encryptedData} = {}} = e;
                                if (encryptedData && iv) {
                                    // wxLogin();
                                    setTimeout(() => {
                                        const session_key = Taro.getStorageSync('session_key') || '';
                                        const openid = Taro.getStorageSync('openid') || '';
                                        if (openid && session_key) {
                                            Taro.request({
                                                url: `${base}/mini/wxLogin`,
                                                data: {
                                                    encryptedData,
                                                    iv,
                                                    openid,
                                                    sessionKey: session_key
                                                },
                                                header: {
                                                    "content-type": "application/json",
                                                    "appid": 'wx52f6aba688ce70f6',
                                                    "Authorization": accessToken ? "Bearer " + accessToken : '',
                                                },
                                                method: "POST",
                                            }).then((res) => {
                                                const {data: {code, data: {phoneNumber: phone, token} = {}} = {}} = res;
                                                if (code === 200) {
                                                    Taro.showToast({
                                                        title: '登录成功',
                                                        icon: 'success'
                                                        // duration: 2000
                                                    })
                                                    Taro.setStorageSync('isLogin', true);
                                                    Taro.setStorageSync('access_token', token);
                                                    Taro.setStorageSync('phoneNumber', phone);
                                                    dispatch({
                                                        type: 'wallet/getBalance'
                                                    })
                                                    dispatch({
                                                        type: 'stations/getChargingOrderInfo'
                                                    })
                                                    // dispatch({
                                                    //     type: 'stations/attendActivity'
                                                    // })
                                                    dispatch({
                                                        type: 'stations/getMyCoupons'
                                                    });
                                                    dispatch({
                                                        type: 'stations/getMyCouponsByStation'
                                                    })
                                                    setOpen(false)
                                                } else {
                                                    Taro.showToast({
                                                        title: '登录失败,请重试',
                                                        icon: 'none'
                                                    })
                                                }
                                            });
                                        }
                                    }, 500)
                                }
                            }}
                        >确定</AtButton>
                    </View>
                </AtModalAction>
            </AtModal>
        </View>
    )
}

function mapStateToProps({
                             stations: {currentStation, rateDetail = []} = {},
                             loading: {effects: {"stations/initDetail": loading = false} = {}} = {},
                         }) {
    return {
        currentStation,
        rateDetail,
        loading,
    };
}

export default connect(mapStateToProps)(Index);
